<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class MY_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();

        //tmp:
        $this->session->set_userdata('member_id', 1);
        
        $this->load->helper('language');
        $this->load->helper('url');
        $this->load->helper('util');
        $this->load->library('parser');
        $this->load->helper('html');
        loadLanguage();
        
        $this->control = trim($this->uri->segment(1));
        if ($this->control != 'language' || $this->control != 'login') {
            $this->session->set_userdata('his',  $this->uri->uri_string());
        } 

        if (trim($this->uri->segment(1)) == 'admin') {
            $this->template->set_template('admin');
            $user = $this->session->userdata('user');
            if(!empty ($user))
            $this->template->write('fullname', $this->session->userdata('user')->lastname . ' ' . $this->session->userdata('user')->firstname);
            if (trim($this->uri->segment(3)) != 'delete'
                    AND trim($this->uri->segment(3)) != 'edit'
                    AND trim($this->uri->segment(3)) != 'save'
                    AND trim($this->uri->segment(3)) != 'create'
                    AND trim($this->uri->segment(3)) != 'change_position') {
               // $_SESSION['his_adm'] = $this->uri->uri_string();
                $this->session->set_userdata('his_adm', $this->uri->uri_string());
            } else{
                $his = $this->session->userdata('his_adm');
                if (empty($his))
                    $this->session->set_userdata('his_adm', 'admin/home');
            }
        }
        else{
            //$this->template->set_template('home');
            //$this->load->model('counter_model', 'counter', true);
            //print_r( $this->counter->show_counter());
            //$counter = $this->counter->show_counter();
            //$this->template->add_region('total_access');
            
            //$this->template->write('total_access',  $counter['total']);
            //$this->template->write('total_online',  $counter['online']);
            
            //$this->setBackground();
        }

        //echo '<br><br><br> My lang =  ___' . $_SESSION['lang'] . '<br>';
        //echo time();
        $this->base_url = $this->config->item('base_url');
        $this->current_url = current_url();
        //initLanguage();
        //$this->lang->load('vnt', $this->session->userdata('lang'));
        //$this->lang->load('common', $this->config->item('language'));
        loadLanguage();
        $this->lang_code = getLangCode();
        $this->name_field = $this->lang_code . '_name';
        $this->description_field = $this->lang_code . '_description';

        if ($this->lang_code == 'vi')
            $this->set_lang = '<a href="' . base_url() . 'language/en">' . lang('english') . '</a>';
        else
            $this->set_lang = '<a href="' .  base_url() . 'language/vi">' . lang('vietnamese') . '</a>';

        //$this->load->model('news_category_model', 'category', true);
        //$this->setTemplate(array('admin/header.tpl', 'admin/product_categories.tpl', 'admin/index.tpl', 'admin/product_categories_item.tpl'));

       // $this->setTopmenu();
        // Tpm:
        $this->load->model('user_model', 'user', true);
        
        $user = $this->user_info = $this->session->userdata('user');

        if (!empty ($user)) {
            
            $this->fullname =$user->lastname . ' ' . $user->firstname;
        }
        else
            $this->fullname = '';

       
    }

    function setBackground(){
        $module = $this->uri->segment(1);
        $code = 'BG-ABOUT';
        if($module == 'project'){
            $code = 'BG-PROJECT';
            $fucn = $this->uri->segment(3, '');
            if($fucn == 'villa')
                $code = 'BG-VILLA';
            else if($fucn == 'town')
                $code = 'BG-TOWN';
            else if($fucn == 'other')
                $code = 'BG-OTHER';
        }
        else if($module == 'consultant'){
            $code = 'BG-CONSULTANT';
        }
        else if($module == 'about'){
            $code = 'BG-ABOUT';
        }
        else if($module == 'service'){
            $code = 'BG-SERVICE';
        }
        
        $this->load->model('config_model', 'configsite', true);
        
        $cf = $this->configsite->getByCode($code);
        
        $background = $cf['config_value'];
        
        $this->template->write('background',  $background);
       
    }
    
    function buildFrontEndTopMenu($parent_category_friendly_url = '', $category_friendly_url = ''){
    	$this->load->model('ncategory_model', 'ncategory', true);
    	
    	$this->load->library('parser');
    	$data['categories'] = $this->ncategory->getAll(20, 0, 0, 1);
    	
    	$link_rewrite = $parent_category_friendly_url; //trim($this->uri->segment(1));
    	
    	if (empty($link_rewrite))
    		$link_rewrite = trim($this->uri->segment(1));
    	
    	$about = '';
    	
    	for ($i = 0; $i < count($data['categories']); $i++){
    		
    	}
    	
    	for ($i = 0; $i < count($data['categories']); $i++){
    		if("thong-tin-ig" == $data['categories'][$i]->link_rewrite){
    			$about = $data['categories'][$i];
    			unset($data['categories'][$i]);
    			break;
    		}
    	}
    	
    	$data['categories'] = array_merge(array($about), $data['categories']);
    	
    	
    	foreach ($data['categories'] as &$item){
    		//print_r($item);
    		if($link_rewrite == $item->link_rewrite)
    			$item->selected = 'selected';
    		else 
    			$item->selected = '';
    		
    			$item->scategories =  $this->ncategory->getAll(20, 0, $item->id_ncategory, 1);
    			foreach ($item->scategories as &$sitem){
    				$sitem->scname = $sitem->cname;
    				$sitem->slink_rewrite = $sitem->link_rewrite;
    				$sitem->url = site_url($item->link_rewrite . '/' . $sitem->link_rewrite);
    			}
    			//$data['scategories'] = $this->ncategory->getAll(20, 0, $item->id_ncategory, 1);
    	}
    	
    	$data['categories1'] = $data['categories'];
    	
    	//print_r($data['categories']);
    	$topmenu = $this->parser->parse('default/front_end/view_top_menu', $data, true);
    	// TMP close:
    	//$this->template->write('top_menu',  $topmenu);
    }
    
    
	function buildSlider(){
    	$this->load->model('slider_model', 'slider', true);
    	
    	//$this->load->library('parser');
    	
    	$data['rows'] = $this->slider->getAll(0, 30, 1, 0);
    	$link_rewrite = trim($this->uri->segment(1));
    	foreach ($data['rows'] as &$item){
    		$item['image'] = img(array('src'=>base_url(SLIDER_IMAGE_PATH . $item['image']), 'alt'=>$item['vi_title'], 'width'=>'1002', 'height'=>'256', ));
    	}
    	
    	//print_r($data['categories']);
    	$slider = $this->parser->parse('default/front_end/view_slider', $data, true);
    	$this->template->write('slider',  $slider);
    }
    
    
	function buildSliderRemove(){
    	$this->load->model('ncategory_model', 'ncategory', true);
    	
    	$this->load->library('parser');
    	$data['categories'] = $this->ncategory->getAll(20, 0, 0, 1);
    	$link_rewrite = trim($this->uri->segment(1));
    	foreach ($data['categories'] as &$item){
    		//print_r($item);
    		if($link_rewrite == $item->link_rewrite)
    			$item->selected = 'selected';
    		else 
    			$item->selected = '';
    		
    			$item->scategories =  $this->ncategory->getAll(20, 0, $item->id_ncategory, 1);
    			foreach ($item->scategories as &$sitem){
    				$sitem->scname = $sitem->cname;
    				$sitem->slink_rewrite = $sitem->link_rewrite;
    				$sitem->url = site_url($item->link_rewrite . '/' . $sitem->link_rewrite);
    			}
    			//$data['scategories'] = $this->ncategory->getAll(20, 0, $item->id_ncategory, 1);
    			
    	}
    	
    	$data['categories1'] = $data['categories'];
    	
    	//print_r($data['categories']);
    	$topmenu = $this->parser->parse('default/front_end/view_top_menu', $data, true);
    	$this->template->write('top_menu',  $topmenu);
    }
    
    function buildMenu() {
        $_tab = trim($this->uri->segment(2));
        $this->menu = '';
        $sub_menu = '';
        $class = 'sub_menu_admin_01';
        $pclass = "sub_menu_admin";
        //$this->setTemplate(array('admin/menu_item.tpl', 'admin/sub_menu_item.tpl'));
        $this->load->model('tab_model', 'tab', true);

        $user = $this->session->userdata('user');
        //$employee->id_profile = 10 ; // TEMP

        $menus = $this->tab->getAllByAccess(0, $user->id_profile, $_tab);
        
        //print_r($menus);
        for ($i = 0; $i < count($menus); $i++) {
            $menu = $menus[$i];
            if ($_tab == $menu->class_name OR ($_tab == $menu->sub_default AND $_tab != '' AND $menu->sub_default != null)) {
                //$class = 'class = "active"';
                $pclass = "sub_menu_admin_active";
                $sub_menus = $this->tab->getAllByAccess($menu->id, $user->id_profile);
                for ($j = 0; $j < count($sub_menus); $j++) {
                    $sub_label = $sub_menus[$j]->vi_name;
                    $sub_image = $this->base_url . $sub_menus[$j]->icon;
                    $url = site_url ( 'admin/' . $sub_menus[$j]->class_name);
                    if ($_tab == $sub_menus[$j]->class_name)
                        $class = 'sub_menu_admin_01_active';
                    else
                        $class = 'sub_menu_admin_01';
                    //$this->sub_menu .= eval($this->loadTemplate('admin/sub_menu_item.tpl'));
                    $sub_menu .= $this->load->view('admin/sub_menu_item', array('class'=>$class, 'url'=>$url, 'sub_label'=>$sub_label), true);
                }
            }
            else {
                //$class = '';
                $pclass = "sub_menu_admin";
            }

            $url = site_url( 'admin/' . $menu->class_name);
            $image = $this->base_url . /* 'images/tab/' . '8.gif' ;// */ $menu->icon;
            $label = $menu->vi_name;
            //$this->menu .= eval($this->loadTemplate('admin/menu_item.tpl'));
            $this->menu .= $this->load->view('admin/menu_item', array('pclass'=>$pclass, 'url'=>$url, 'label'=>$label, 'sub_menu'=>$sub_menu), true);
            $sub_menu = '';
        }

        /*$tmp = $items[$control];

          foreach($tmp as $k => $v){
          $label = $k;
          $result  .= eval($this->loadTemplate('left_pitem_menu.tpl'));
          foreach($v as $function => $label){
          $url = $this->base_url .'admin/'. $control . '/' . $function;
          $result  .= eval($this->loadTemplate('left_item_menu.tpl'));
          }

          }

         return $result; */
         $this->template->write('menu',  $this->menu);
         //echo $this->menu;
        return $this->menu;
    }

    function buildPage($data = array()) {
        $data['header'] = $this->load->view('default/common/header', '', true);
        $data['footer'] = $this->load->view('default/common/footer', '', true);
        if (!isset($data['content']))
            $data['content'] = '';

        $this->load->view('default/common/main', $data);
    }

    function checkLogin() {
        $user = $this->session->userdata('user');
		if(empty ($user))
                redirect('admin/login');
                           
    }

    function checkPermission() {
        $class_name = $this->uri->segment('2', 'home');
        $action = $this->uri->segment('3', 'view');
        if ($action == 'create')
            $action = 'add';
        elseif ($action == 'view_tree' OR $action == 'detail')
            $action = 'view';
        elseif ($action == 'change_order' || $action == 'change_access')
            $action = 'edit';
        elseif ($action == 'save') {
            $id = (int) $this->input->post('txtID');
            if ($id)
                $action = 'edit';
            else
                $action = 'add';
        }
        
        $user = $this->session->userdata('user');


        $this->load->model('access_model', 'access', true);
        $perm = $this->access->checkAccess( $user->id_profile, $class_name, $action);
       
        if (!$perm) {

            $this->main = $this->load->view('admin/warning', array(), true);

            $this->execute();
            exit();
        }

        return true;
    }

    function buildSuportBox() {
        $this->load->model('suport_model', 'suport', true);
        $suports = $this->suport->getAll();
        return $this->load->view('front_end/suport', array('rows' => $suports), true);
    }

    function buildLinkWebBox() {
        $this->load->model('link_model', 'link', true);
        $links = $this->link->getAll();
        return $this->load->view('front_end/link_web_box', array('rows' => $links), true);
    }

    function buildAdv() {
        $data = array();
        $this->load->model('adv_model', 'adv', true);
        $this->left_adv = '';
        $this->right_adv = '';
        $this->bottom_adv = '';
        $advs = $this->adv->getAll();
        $tmp = array();
        for ($i = 0; $i < count($advs); $i++) {
            $tmp[$advs[$i]->position][] = $advs[$i];
        }

        // build right adv:
        if (isset($tmp['right'])) {
            $data['rows'] = $tmp['right'];
            $this->right_adv = $this->load->view('front_end/right_adv', $data, true);
        }

        // build left adv:
        if (isset($tmp['left'])) {
            $data['rows'] = $tmp['left'];
            $this->left_adv = $this->load->view('front_end/left_adv', $data, true);
        }

        // build bottom adv:
        if (isset($tmp['bottom'])) {
            $data['rows'] = $tmp['bottom'];
            $this->bottom_adv = $this->load->view('front_end/bottom_adv', $data, true);
        }
    }

    function buildSearchBox() {
        $data = array();
        $ddl = $this->buidDDProductCategoryListById("id_pcategory", -1, 'input');
        $data['ddl'] = $ddl;
        $this->search_box = $this->load->view('front_end/search_box', $data, true);
    }

    function buidDDProductCategoryListById($name, $default, $class = '', $action = '') {
        //$this->load->model('pcategory_model', 'category', true);
        $categories = $this->pcategory->getAll();
        $this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        //$name = 'Parent';
        $value = '-1';
        $selected = '';
        $space = '';
        $label = lang('all');
        // $class = '';
        //$action = '';
        $style = '';

        $tmp = array();
        for ($i = 0; $i < count($categories); $i++) {
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
        }

        $options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOptionById($tmp/* $categories */, 0, $default);
        return eval($this->loadTemplate('admin/ddl.tpl'));
    }

    function getCategoryOptionById($tmp/* $categories */, $parent = 0, $default = 0, $space = '&nbsp;') {
        $items = '';
        /* if(!$categories){
          $categories = $this->pcategory->getAll();
          } */
        /* $tmp = array();
          for($i = 0; $i <count($categories); $i++){
          $category = $categories[$i];
          //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
          $tmp[$category->code_parent][$category->code] = $category;
          } */
        //print_r($tmp);
        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                //$parent = $v->id_pcategory;
                //$value = $v->id_pcategory;
                //echo '<br>\n'.$parent . '_\n';
                $parent = $v->id_pcategory;
                $value = $v->id_pcategory;
                $label = $v->vi_name;
                $selected = '';
                if ($value == $default)
                    $selected = 'selected';
                $items .= eval($this->loadTemplate('admin/option_ddl.tpl'));

                $items .=$this->getCategoryOptionById($tmp/* $categories */, $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }

        return $items;
    }

    function buildBestSellProductBox($num_record = 3) {
        $this->load->model('product_model', 'product', true);
        $products = $this->product->getBestSellProduct(5);
        //print(count($products));
        if (count($products) > 0) {
            $data = array();
            $data['rows'] = $products;
            $this->best_sell_product = $this->load->view('front_end/best_sell_product', $data, true);
        }
        else
            $this->best_sell_product = '';
    }

    function addHeader($header) {
        $this->header .= $header;
    }

    function buildPmenu() {
        $this->setTemplate(array('pmenu_item.tpl', 'pmenu.tpl'));

        $this->load->model('pcategory_model', 'pcategory', true);
        $this->load->model('product_model', 'product', true);

        $id_selected = intval($this->uri->segment(3, 0));
        $default = 0;

        $control = trim($this->uri->segment(1));
        if (($control == 'products' OR $control == 'prices') AND $id_selected > 0) {
            if (trim($this->uri->segment(1)) == 'info') {
                $pro = $this->product->getById($id_selected);
                if ($pro)
                    $id_selected = $pro->id_pcategory;
            }

            $ids = getTrack($id_selected);
            //print_r($ids);
            if (count($ids) > 0)
                $default = $ids[0]->id_pcategory;
        }

        //if($control!='prices')
        //$control = 'products';

        $categories = $this->pcategory->getByParentCode('');
        $items = '';
        $name_field = $this->lang_code . '_name';

        for ($i = 0; $i < count($categories); $i++) {
            $link = $this->base_url . $categories[$i]->module . '/view/' . $categories[$i]->id_pcategory;
            $name = $categories[$i]->$name_field;

            if ($categories[$i]->id_pcategory == $default)
                $class = 'active_hoz_menu';
            else
                $class = '';

            $items .= eval($this->loadTemplate('pmenu_item.tpl'));
        }

        return eval($this->loadTemplate('pmenu.tpl'));
    }

    function loadErrorMessage($message) {
        $this->setTemplate('error_message.tpl');
        $error_message = $message;
        return eval($this->loadTemplate('error_message.tpl'));
    }

    function execute($content = '') {

        $control = $this->uri->segment(1);


        $this->setTemplate(array('front_end/login.tpl'));
        //$this->menu = $this->buildMenu();
        echo eval($this->loadTemplate("front_end/login.tpl"));
    }
    
    function test(){
    	$abc = 'sss sd sd sd dsd';
    	echo $abc;
    	
    	$control = $this->uri->segment(1);
		
    	 $temp_name = '';
    	 
        $this->setTemplate(array('front_end/login.tpl'));
        //$this->menu = $this->buildMenu();
        echo eval($this->loadTemplate("front_end/login.tpl"));
        
        $temp_name = '';
        
    if (isset($this->templates[$temp_name])) {

            return "return \"" . str_replace("\"", "\\\"", $this->templates[$temp_name]) . "\n\";";
        } else {

            die("<b>Template $temp_name</b> isn't found!");
        }
        
    	return $abc;
    }

    /*
      Lan vet ve danh muc cha.
     */

    function loadTemplate($temp_name) {

        if (isset($this->templates[$temp_name])) {

            return "return \"" . str_replace("\"", "\\\"", $this->templates[$temp_name]) . "\n\";";
        } else {

            die("<b>Template $temp_name</b> isn't found!");
        }
    }

    function setTemplate($file) {

        if ($file == '')
            return;

        $array_file = array();

        if (!is_array($file))
            $array_file[0] = $file;
		
            
            
        else
            $array_file = $file;

        foreach ($array_file as $temp_name) {
            if (!isset($this->templates[$temp_name])) {
                $path = APPPATH . 'views/' . $temp_name;
                echo "<br>PATH=" . $path;
                $fp = @fopen($path, 'r');

                if (!$fp)
                    die("Can't open <b>template file $path</b> for reading!");

                else {

                    $this->templates[$temp_name] = fread($fp, filesize($path));

                    fclose($fp);
                }
            } // end if
        } // end for
    }

    function testCommit(){
    	// Khoi add for test commit.
    }
    
    function checkUserLogin() {
        $user = $this->session->userdata('user');
		if(empty ($user)){
             return false;
		}
		return true;
		
    }
}

?>
